<?php

/**

 * 个人事务
 * 
 * @access  public 
 * @author  qiaoshoujuan<qiao_sj@jsumt.com.cn> 
 */

namespace Home\Controller;

use Think\Controller;

class PersonalController extends BaseController {

    public function _initialize() {
        parent::_initialize();
        $this->title = '公告通知';

        //获取公告分类
        $map['parent_no'] = 'notify';
        $this->notice_code = M('sys_code')->where($map)->order('code_no')->select();

        //获取新闻分类
        $map = [];
        $map['parent_no'] = 'news';
        $this->news_code = M('sys_code')->where($map)->order('code_no')->select();

        //获取公文分类
        $map = [];
        $map['parent_no'] = 'document';
        $this->document_code = M('sys_code')->where($map)->order('code_no')->select();

        //获取用户的辅助角色
        $userinfo = M('user')->field('user_id,user_name,user_priv,user_priv_other')->select();

        //获取用户可发布公告通知的用户
        $notice_menu_id = M('backmenu')->where('name like "%公告通知管理%"')->getField('id');
        $privs = M('user_priv')->field('user_priv,priv_name,priv_no')->where('menu_id like "%' . $notice_menu_id . '%"')->select();
        unset($map);
        foreach ($userinfo as $k => $v) {
            foreach ($privs as $key => $value) {
                if ($value['user_priv'] == $v['user_priv']) {
                    $notice_users[] = $v;
                }
                if ($v['user_priv_other']) {
                    $priv_other_arr = explode(',', substr($v['user_priv_other'], 0, -1));
                    if (in_array($value['user_priv'], $priv_other_arr)) {
                        $notice_users[] = $v;
                    }
                }
            }
        }
        $notice_users = array_unique($notice_users, SORT_REGULAR);
        sort($notice_users);
        $this->notice_users = $notice_users;
        //获取用户可管理新闻的用户
        $news_menu_id = M('backmenu')->where('name like "%新闻管理%"')->getField('id');
        $privs = M('user_priv')->field('user_priv,priv_name,priv_no')->where('menu_id like "%' . $news_menu_id . '%"')->select();
        unset($map);
        foreach ($userinfo as $k => $v) {
            foreach ($privs as $key => $value) {
                if ($value['user_priv'] == $v['user_priv']) {
                    $news_users[] = $v;
                }
                if ($v['user_priv_other']) {
                    $priv_other_arr = explode(',', substr($v['user_priv_other'], 0, -1));
                    if (in_array($value['user_priv'], $priv_other_arr)) {
                        $news_users[] = $v;
                    }
                }
            }
        }
        $news_users = array_unique($news_users, SORT_REGULAR);
        sort($news_users);
        $this->news_users = $news_users;

        //获取用户可发布公文的用户
        $document_menu_id = M('backmenu')->where('name like "%公文发布管理%"')->getField('id');
        $privs = M('user_priv')->field('user_priv,priv_name,priv_no')->where('menu_id like "%' . $document_menu_id . '%"')->select();
        unset($map);
        foreach ($userinfo as $k => $v) {
            foreach ($privs as $key => $value) {
                if ($value['user_priv'] == $v['user_priv']) {
                    $document_users[] = $v;
                }
                if ($v['user_priv_other']) {
                    $priv_other_arr = explode(',', substr($v['user_priv_other'], 0, -1));
                    if (in_array($value['user_priv'], $priv_other_arr)) {
                        $document_users[] = $v;
                    }
                }
            }
        }
        $document_users = array_unique($document_users, SORT_REGULAR);
        sort($document_users);
        $this->document_users = $document_users;
    }

    //获取公告数据
    public function getNoticeData($con, $p, $limit) {
        $map = [];
        if (isset($con['is_read']) && $con['is_read'] == 2) {
            $this->is_read = $con['is_read'];
            $map['readers'] = array('like', '%' . session('user_id') . '%');
        }
        if (isset($con['from_id']) && $con['from_id'] != '') {
            $this->from_id = $con['from_id'];
            $map['from_id'] = array('like', '%' . $con['from_id'] . '%');
        }
        if (isset($con['type_id']) && $con['type_id'] != '') {
            $this->type_id = $con['type_id'];
            $map['type_id'] = array('eq', $con['type_id']);
        }
        if (isset($con['subject']) && $con['subject'] != '') {
            $this->subject = $con['subject'];
            $map['subject'] = array('like', '%' . $con['subject'] . '%');
        }
        if (isset($con['send_time']) && $con['send_time'] != '') {
            $this->send_time = $con['send_time'];
            $map['send_time'] = array('like', '%' . $con['send_time'] . '%');
        }
        if (isset($con['content']) && $con['content'] != '') {
            $this->content = $con['content'];
            $map['content'] = array('like', '%' . $con['content'] . '%');
        }
        if ($con['is_read'] == 1 || $con || empty($con)) {
            if ($con['is_read'] == 1) {
                $map['readers'] = array(array('notlike', '%' . session('user_id') . '%'), array('exp', 'IS NULL'), 'or');
                $this->is_read = $con['is_read'];
            }
            //部门条件符合
            $where['to_id'] = array(array('like', '%ALL_DEPT%'), array('like', '%' . session('dept_id') . '%'), 'or');

            //角色条件符合
            $curUserPriv = session('user_priv') . ',' . session('user_priv_other');
            $curUserPrivArr = explode(',', substr($curUserPriv, 0, -1));
            foreach ($curUserPrivArr as $priv) {
                $privCon[] = array(array('like', '%' . ',' . $priv . ',' . '%'), array('like', $priv . ',%'), 'or');
            }
            $privCon[] = 'or';
            $where['priv_id'] = $privCon;

            //人员符合
            $where['user_id'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map[] = $where;
            $map['_logic'] = 'and';
        }


        $count = M('notify')->where($map)->count();
        if ($limit) {
            $notify = M('notify')->field('notify_id,from_dept,from_id,to_id,subject,content,send_time,begin_date,end_date,priv_id,user_id,type_id,readers')->where($map)->order('send_time desc')->page($p, $limit)->select();
        } else {
            $notify = M('notify')->field('notify_id,from_dept,from_id,to_id,subject,content,send_time,begin_date,end_date,priv_id,user_id,type_id,readers')->where($map)->order('send_time desc')->select();
        }

//        echo M()->getLastSql();
        foreach ($notify as $k => $v) {
            $deptName = [];
            $notify[$k]['begin_date'] = date("Y-m-d", $v['begin_date']);
            $notify[$k]['end_date'] = date("Y-m-d", $v['end_date']);

            if ($v['to_id'] == 'ALL_DEPT') {
                $notify[$k]['to_id'] = '全体部门';
            } else {
                $deptNameArr = M('department')->field('dept_name')->where('dept_id in(' . substr($v['to_id'], 0, -1) . ')')->select();
                foreach ($deptNameArr as $key => $value) {
                    $deptName[] = $value['dept_name'];
                }
                $notify[$k]['to_id'] = implode(',', $deptName);
            }
            if ($v['priv_id']) {//发布角色范围
                $userPrivArr = M('user_priv')->field('priv_name')->where('user_priv in(' . substr($v['priv_id'], 0, -1) . ')')->select();
                foreach ($userPrivArr as $key => $value) {
                    $privName[] = $value['priv_name'];
                }
                $notify[$k]['priv_id'] = implode(',', $privName);
            }
            if ($v['user_id']) {//发布人员范围
                $userNameArr = explode(',', substr($v['user_id'], 0, -1));
                foreach ($userNameArr as $u_value) {
                    $userName[] = M('user')->where('user_id = "' . $u_value . '"')->getField('user_name');
                }
                $notify[$k]['user_id'] = implode(',', $userName);
            }
            if (strstr($v['readers'], session('user_id'))) {
                $notify[$k]['is_read'] = 2; //已读
            } else {
                $notify[$k]['is_read'] = 1; //未读
            }
        }
        $notify['count'] = $count;
        return $notify;
    }

    //公告列表
    public function notice() {
        $p = I('get.p');
        $limit = $this->limit;
        $con = I('get.');
        $notify = $this->getNoticeData($con, $p, $limit);
        $count = $notify['count'];
        unset($notify['count']);
        $this->notify = $notify;
        $this->count = $count;
        $this->page = $this->pageLists($count, $limit);
        $this->display();
    }

    //公告内容读取
    public function readNotify() {
        $notify_id = I('notify_id');
        if (I('is_manage')) {
            $this->is_manage = I('is_manage');
        }
        if (I('model')) {
            $this->model = I('model');
        }

        if (IS_AJAX) {
            $lists = $this->getNoticeData($con, '', '');
            unset($lists['count']);
            $len = count($lists) - 1;
            $status = I('status');
            foreach ($lists as $key => $row) {
                if ($row['notify_id'] == $notify_id) {
                    if ($status == 'prev') {
                        //取前一条
                        $notify = $key != 0 ? $lists[$key - 1] : [];
                    } else {
                        $notify = $key < $len ? $lists[$key + 1] : [];
                    }
                }
            }
            if (empty($notify)) {
                $return['status'] = 0;
                $return['info'] = $status == 'prev' ? '已经是第一条公告' : '已经是最后一条公告';
            } else {
                $return['url'] = U('readNotify', array('notify_id' => $notify['notify_id']));
                $return['notify_id'] = $notify['notify_id'];
                $return['status'] = 1;
            }
            $this->ajaxReturn($return);
        }

        $map['notify_id'] = $notify_id;
        $notify = M('notify')->field('notify_id,from_id,from_dept,to_id,subject,content,send_time,type_id,auditer,keyword,attachment_id,attachment_name,last_editor,last_edit_time,readers,uploads,uploads_url')->where($map)->find();
        $notify['keyword'] = str_replace(',', '&nbsp', $notify['keyword']);
        if ($notify['attachment_name']) {
            $notify['attachment_name'] = explode('*', substr($notify['attachment_name'], 0, -1));
        }
        if ($notify['uploads']) {
            $notify['uploads'] = explode(';', $notify['uploads']);
            $notify['uploads_url'] = explode(';', $notify['uploads_url']);
        }
        //更新阅读者
        if (!strstr($notify['readers'], session('user_id'))) {
            $readers = $notify['readers'] . session('user_id') . ",";
            $sql = "update `notify` set readers = '" . $readers . "' where notify_id = " . $notify_id;
            M('')->execute($sql);
        }
//        echo '<pre>',print_r($notify);die;
        $this->data = $notify;
        $this->display();
    }

    //获取新闻数据
    public function getNewsData($con, $p, $limit) {
        $map = [];
        if (isset($con['is_read']) && $con['is_read'] == 2) {
            $this->is_read = $con['is_read'];
            $map['readers'] = array('like', '%' . session('user_id') . '%');
        }
        if (isset($con['provider']) && $con['provider'] != '') {
            $this->provider = $con['provider'];
            $map['provider'] = array('like', '%' . $con['provider'] . '%');
        }
        if (isset($con['type_id']) && $con['type_id'] != '') {
            $this->type_id = $con['type_id'];
            $map['type_id'] = array('eq', $con['type_id']);
        }
        if (isset($con['subject']) && $con['subject'] != '') {
            $this->subject = $con['subject'];
            $map['subject'] = array('like', '%' . $con['subject'] . '%');
        }
        if (isset($con['news_time']) && $con['news_time'] != '') {
            $this->send_time = $con['news_time'];
            $map['news_time'] = array('like', '%' . $con['news_time'] . '%');
        }
        if (isset($con['content']) && $con['content'] != '') {
            $this->content = $con['content'];
            $map['content'] = array('like', '%' . $con['content'] . '%');
        }
        if ($con['is_read'] == 1 || $con || empty($con)) {
            if ($con['is_read'] == 1) {
                $map['readers'] = array(array('notlike', '%' . session('user_id') . '%'), array('exp', 'IS NULL'), 'or');
                $this->is_read = $con['is_read'];
            }
            //部门条件符合
            $where['to_id'] = array(array('like', '%ALL_DEPT%'), array('like', '%' . session('dept_id') . '%'), 'or');

            //角色条件符合
            $curUserPriv = session('user_priv') . ',' . session('user_priv_other');
            $curUserPrivArr = explode(',', substr($curUserPriv, 0, -1));
            foreach ($curUserPrivArr as $priv) {
                $privCon[] = array(array('like', '%' . ',' . $priv . ',' . '%'), array('like', $priv . ',%'), 'or');
            }
            $privCon[] = 'or';
            $where['priv_id'] = $privCon;

            //人员符合
            $where['user_id'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map[] = $where;
            $map['_logic'] = 'and';
        }


        $count = M('news')->where($map)->count();
        if ($limit) {
            $news = M('news')->field('news_id,provider,to_id,subject,content,news_time,priv_id,user_id,type_id,readers,click_count')->where($map)->order('news_time desc')->page($p, $limit)->select();
        } else {
            $news = M('news')->field('news_id,provider,to_id,subject,content,news_time,priv_id,user_id,type_id,readers,click_count')->where($map)->order('news_time desc')->select();
        }

//        echo M()->getLastSql();
        foreach ($news as $k => $v) {
            $deptName = [];
            if ($v['to_id'] == 'ALL_DEPT') {
                $news[$k]['to_id'] = '全体部门';
            } else {
                $deptNameArr = M('department')->field('dept_name')->where('dept_id in(' . substr($v['to_id'], 0, -1) . ')')->select();
                foreach ($deptNameArr as $key => $value) {
                    $deptName[] = $value['dept_name'];
                }
                $news[$k]['to_id'] = implode(',', $deptName);
            }
            if ($v['priv_id']) {//发布角色范围
                $userPrivArr = M('user_priv')->field('priv_name')->where('user_priv in(' . substr($v['priv_id'], 0, -1) . ')')->select();
                foreach ($userPrivArr as $key => $value) {
                    $privName[] = $value['priv_name'];
                }
                $news[$k]['priv_id'] = implode(',', $privName);
            }
            if ($v['user_id']) {//发布人员范围
                $userNameArr = explode(',', substr($v['user_id'], 0, -1));
                foreach ($userNameArr as $u_value) {
                    $userName[] = M('user')->where('user_id = "' . $u_value . '"')->getField('user_name');
                }
                $news[$k]['user_id'] = implode(',', $userName);
            }
            if (strstr($v['readers'], session('user_id'))) {
                $news[$k]['is_read'] = 2; //已读
            } else {
                $news[$k]['is_read'] = 1; //未读
            }
        }
        $news['count'] = $count;
        return $news;
    }

    //新闻列表
    public function news() {
        $p = I('get.p');
        $limit = $this->limit;
        $con = I('get.');
        $news = $this->getNewsData($con, $p, $limit);
        $count = $news['count'];
        unset($news['count']);
        foreach ($news as $k => $v) {
            $news[$k]['comment_count'] = M('news_comment')->where('news_id = ' . $v['news_id'])->count();
        }

        $this->news = $news;
        $this->count = $count;
        $this->page = $this->pageLists($count, $limit);
        $this->display();
    }

    //新闻内容读取
    public function readNews() {
        $news_id = I('news_id');
        if (I('is_manage')) {
            $this->is_manage = I('is_manage');
        }

        $map['news_id'] = $news_id;
        $news = M('news')->where($map)->find();
        $news['keyword'] = str_replace(',', '&nbsp', $news['keyword']);
//        if($news['attachment_name']){
//            $news['attachment_name'] = explode('*',substr($news['attachment_name'],0,-1));
//        }

        $this->uploads = downloadFile($news['attachment_id'], $news['attachment_name'], 'news', $news['uploads'], $news['uploads_url']);

        //发布范围
        if ($news['to_id'] != 'ALL_DEPT') {
            $news['to_id'] = explode(',', substr($news['to_id'], 0, -1));
        }

        $news['priv_id'] = $news['priv_id'] ? explode(',', substr($news['priv_id'], 0, -1)) : '';
        $news['user_id'] = $news['user_id'] ? explode(',', substr($news['user_id'], 0, -1)) : '';
        //更新阅读者
        if (!strstr($news['readers'], session('user_id'))) {
            $readers = $news['readers'] . session('user_id') . ",";
            $sql = "update `news` set readers = '" . $readers . "' where news_id = " . $news_id;
            M('')->execute($sql);
        }

        //更新点击量
        $sql = "update `news` set click_count = click_count + 1 where news_id = " . $news_id;
        M('')->execute($sql);

        //获取最新的5条评论
        $news_comment = M('news_comment')->where('news_id = ' . $news['news_id'])->order('re_time desc')->limit('5')->select();
        foreach ($news_comment as $k => $v) {
            //获取评论回复
            $news_comment[$k]['reply_count'] = M('news_comment')->where('parent_id = ' . $v['comment_id'])->count();

            //判断是否有原贴
            if ($v['parent_id']) {
                $news_comment[$k]['initial_comment'] = M('news_comment')->where('comment_id = ' . $v['parent_id'])->select();
            }

            //判断当前用户是否是新闻发布者、是否该条新闻的评论者，是否有权限删除评论
            if ($v['provider'] == session("user_id") || $v['user_id'] == session("user_id")) {
                $news_comment[$k]['is_del'] = 1;
            }
        }
//        print_r($news);
        $this->user_id = session('user_id');
        $this->data = $news;
        $this->news_comment = $news_comment;
        $this->display();
    }

    //新建公告
    public function saveNotice() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['begin_date'] = $data['begin_date'] ? strtotime($data['begin_date']) : time();
            $data['end_date'] = $data['end_date'] ? strtotime($data['end_date']) : 0;
            $data['to_id'] = $data['dept_ids'] ? implode(',', $data['dept_ids']) : 'ALL_DEPT';
            $data['priv_id'] = implode(',', $data['priv_id']);
            $data['user_id'] = implode(',', $data['participator']);
            $data['top'] = $data['top'] ? 1 : 0;

            //提交审批
            if (!I('get.type')) {
                
                $data['publish'] = 2;
            } else {
                $data['publish'] = 0;
            }

            if ($data['id']) {
                $row = M('notify')->where('notify_id=' . $data['id'])->find();
                if ($data['uploads_url'] && $data['uploads_url'] != $row['uploads_url']) {
                    @unlink('.' . $row['uploads_url']);
                } else {
                    $data['uploads_url'] = $row['uploads_url'];
                }
                $data['last_editor'] = session('user_id');
                $data['last_edit_time'] = date('Y-m-d H:i:s');
                $res = M('notify')->where('notify_id=' . $data['id'])->save($data);
            } else {
                $data['from_dept'] = session('dept_id');
                $data['from_id'] = session('user_id');
                $data['print'] = 1;
                $data['download'] = 1;
                $data['send_time'] = date('Y-m-d H:i:s');

                $res = M('notify')->add($data);
            }
            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('lists', array('type' => 2));
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }

        if (I('notify_id')) {
            $info = M('notify')->where('notify_id=' . I('notify_id'))->find();
            if ($info['to_id'] != 'ALL_DEPT') {
                $this->to_ids = explode(',', $info['to_id']);
            }
            if ($info['priv_id']) {
                $this->priv_ids = explode(',', $info['priv_id']);
            }
            if ($info['user_id']) {
                $this->user_ids = explode(',', $info['user_id']);
            }

            //获取pc端上传的附件
            if ($info['attachment_name']) {
                $pcNames = downloadFile($info['attachment_id'], $info['attachment_name'], 'notify');
            }

            $this->id = I('notify_id');
            $this->info = $info;
        }

        $this->display();
    }

    // 获取上一篇或下一篇公告
    public function getOtherNotify() {
        $type = I('type');
        $id = I('id');
        $status = I('status');
        $lists = $this->getNoticeData('', $type);
        $len = count($lists) - 1;
        if ($type) {
            foreach ($lists as $key => $row) {
                if ($row['notify_id'] == $id) {
                    if ($status == 'prev') {
                        //取前一条
                        $notify = $key != 0 ? $lists[$key - 1] : [];
                    } else {
                        $notify = $key < $len ? $lists[$key + 1] : [];
                    }
                }
            }
        } else {
            foreach ($lists as $key => $row) {
                if ($key == 0 && ($row['notify_id'] < $id)) {
                    $arr['notify_id'] = $id;
                    array_unshift($lists, $arr);
                } else if (($key == $len) && ($row['notify_id'] > $id)) {
                    $arr['notify_id'] = $id;
                    array_push($lists, $arr);
                } else if ($row['notify_id'] > $id && $lists[$key + 1]['notify_id'] < $id) {
                    $arr[]['notify_id'] = $id;
                    array_splice($lists, $key + 1, 0, $arr);
                }
            }

            foreach ($lists as $key => $row) {
                if ($row['notify_id'] == $id) {
                    if ($status == 'prev') {
                        //取前一条
                        $notify = $key != 0 ? $lists[$key - 1] : [];
                    } else {
                        $notify = $key < $len ? $lists[$key + 1] : [];
                    }
                }
            }
        }

        if (empty($notify)) {
            $return['status'] = 0;
            $return['info'] = $status == 'prev' ? '已经是第一条公告' : '已经是最后一条公告';
        } else {
            $return['url'] = U('show', array('notify_id' => $notify['notify_id'], 'type' => $type));
            $return['id'] = $notify['notify_id'];
            $return['status'] = 1;
        }
        $this->ajaxReturn($return);
    }

    //上传文件
    public function upload() {
        $this->upfile('./Public/Uploads/notice/');
    }

    //新闻动态评论
    public function commentNews() {
        if (IS_AJAX) {
            $data = I('post.');
            //添加news表
            $cdata['news_id'] = $data['news_id'];
            $cdata['user_id'] = session('user_id');
            $cdata['content'] = $data['content'];
            $cdata['re_time'] = date('Y-m-d H:i:s');
            $res = M('news_comment')->add($cdata);

            if ($res !== false) {
                $return['info'] = '提交成功';
                $return['url'] = U('readNews', array('news_id' => $data['news_id'], 'is_manage' => $data['is_manage']));
            } else {
                $return['info'] = '提交失败';
            }
            $this->ajaxReturn($return);
        }
    }

    //删除新闻评论
    public function delComment() {
        $comment_id = I('comment_id');
        $res = M('news_comment')->where('comment_id=' . $comment_id)->delete();
        $r = M('news_comment')->where('parent_id = ' . $comment_id)->delete();
        if ($res !== false || $r !== false) {
            $return['info'] = '删除成功';
        } else {
            $return['info'] = '删除失败';
        }
        $this->ajaxReturn($return);
    }

    //回复新闻评论
    public function replyComment() {
        $data['parent_id'] = I('comment_id');
        $data['user_id'] = session('user_id');
        $data['news_id'] = I('news_id');
        $data['content'] = I('content');
        $data['re_time'] = date('Y-m-d H:i:s');

        $res = M('news_comment')->add($data);
        if ($res) {
            $return['status'] = '1';
        } else {
            $return['status'] = '0';
        }
        $this->ajaxReturn($return);
    }

    //工作日志
    public function diary() {
        $p = I('get.p');
        $limit = $this->limit;
        $is_view = 0; //用户只能查看自己的
        //当前用户的角色
        $userPriv = session('user_priv_other') ? session('user_priv_other') . session('user_priv') : session('user_priv');
        $priv_no = M('user_priv')->field('priv_no')->where('user_priv in(' . $userPriv . ')')->select();
        foreach ($priv_no as $v) {
            $privArr[] = $v['priv_no'];
        }
        rsort($privArr);
        if (end($privArr) <= 20) {
            $is_view = 1; //可查看全公司
        } elseif (end($privArr) > 20 && end($privArr) <= 40) {
            $is_view = 2; //可查看本部门
        }
        if ($is_view == 1) {
            $where = 'd.user_id = u.user_id';
        } elseif ($is_view == 2) {
            $where = 'd.user_id = u.user_id and u.dept_id in (' . session('dept_id') . ')';
        } else {
            $where = 'd.user_id = u.user_id and u.user_id = "' . session('user_id') . '"';
        }
        $diary = M()->table('diary d,user u')->field('u.user_name,u.head,u.head_url,d.dia_id,d.user_id,d.dia_date,d.dia_time,d.subject,d.content,d.compress_content,d.last_comment_time,d.to_id,d.readers')->where($where)->order('d.dia_date desc')->page($p, $limit)->select();
        foreach ($diary as $k => $v) {
            $diary[$k]['content'] = html_entity_decode($v['content'], ENT_QUOTES, 'UTF-8');
            $comment = M('diary_comment')->where('dia_id = ' . $v['dia_id'])->order('send_time desc')->select();
            if ($comment) {
                foreach ($comment as $key => $value) {
                    $reply = M('diary_comment_reply')->where('comment_id = ' . $value['comment_id'])->select();
                    $comment[$key]['reply'] = $reply;
                    $comment[$key]['timestamp'] = strtotime($value['send_time']);
                }
            }
            $diary[$k]['comment'] = $comment;
            $diary[$k]['comment_count'] = count($comment);
        }
        $count = M()->table('diary d,user u')->where($where)->count();
        $this->diary = $diary;
        $this->is_view = $is_view;
        $this->count = $count;
        $this->page = $this->pageLists($count, $limit);
        $this->display();
    }

    //新建日志
    public function saveDiary() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['user_id'] = session('user_id');
            $data['dia_date'] = substr($data['subject'], 0, 10);
            $data['dia_time'] = date('Y-m-d H:i:s');
            $data['dia_type'] = 1;
            if ($data['dia_id']) {
                $res = M('diary')->where('dia_id = ' . $data['dia_id'])->save($data);
            } else {
                $map['user_id'] = session('user_id');
                $map['dia_date'] = substr($data['subject'], 0, 10);
                $row = M('diary')->where($map)->count();
                if (!$row) {
                $res = M('diary')->add($data);
                } else {
                    $reutrn = ['info' => '请勿重复提交', 'icon' => 5, 'status' => 0];
                }
            }

            if ($res !== false) {
                if ($data['type']) {
                    $return['info'] = '提交成功';
                    $return['parent'] = 1;
                } else {
                    $return['url'] = U('diary');
                    $return['info'] = '操作成功';
                }
                $return['status'] = 1;
            } else {
                $return['status'] = 0;
                $return['info'] = '操作失败';
            }
            $this->ajaxReturn($return);
        }
        $dia_id = I('dia_id');
        if ($dia_id) {
            $diary = M('diary')->where('dia_id = ' . $dia_id)->find();
            $this->diary = $diary;
        }
        $cur_date = date('Y-m-d', time());
        $weeknames = array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
        $dateArr = explode("-", $cur_date);

        $week = date("w", mktime(0, 0, 0, $dateArr[1], $dateArr[2], $dateArr[0]));
        $weekname = $weeknames[$week];
        $subject = $cur_date . " " . $weekname . " 日志";
        $this->subject = $subject;
        $this->dia_id = $dia_id;
        $this->display();
    }

    //删除日志
    public function delDiary() {
        $dia_id = I('dia_id');
        $res = M('diary')->where('dia_id = ' . $dia_id)->delete();
        $r = M('diary_comment')->where('dia_id = ' . $dia_id)->delete();
        $dia_comment = M('diary_comment')->where('dia_id = ' . $dia_id)->select();
        foreach ($dia_comment as $k => $v) {
            $result = M('diary_comment_reply')->where('comment_id = ' . $v['comment_id'])->delete();
        }
        if ($res !== false || $r !== false) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //评论日志
    public function commentDiary() {
        $data = I('get.');
        $data['user_id'] = session('user_id');
        $data['send_time'] = date('Y-m-d H:i:s');
        $res = M('diary_comment')->add($data);
        if ($res) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //回复日志评论
    public function replyDiary() {
        $data = I('get.');
        $data['reply_comment'] = $data['content'];
        $data['replyer'] = session('user_id');
        $data['reply_time'] = date('Y-m-d H:i:s');
        $data['comment_id'] = $data['comment_id'];
        $res = M('diary_comment_reply')->add($data);
        if ($res) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //删除日志评论
    public function delDiaryComment() {
        $data = I('get.');
        if ($data['type'] == 'comment') {
            $res = M('diary_comment')->where('comment_id = ' . $data['comment_id'])->delete();
            $r = M('diary_comment_reply')->where('comment_id = ' . $data['comment_id'])->delete();
        } elseif ($data['type'] == 'reply') {

            $res = M('diary_comment_reply')->where('reply_id = ' . $data['reply_id'])->delete();
        }
        if ($res !== false) {
            $return['status'] = 1;
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //日志检索
    public function searchDiary() {
        if (IS_AJAX) {
            ini_set('memory_limit', '-1');
            $data = I('get.');
            $p = I('get.p');
            $limit = 10;
            $start = $limit * ($p - 1);
            $diary = M('diary')->field('dia_id,user_id,dia_date,dia_time,subject,content,readers')->where('user_id = "' . $data['user_id'] . '"')->order('dia_date desc')->page($p, $limit)->select();
            $count = M('diary')->where('user_id = "' . $data['user_id'] . '"')->count();
            foreach ($diary as $k => $v) {
                $diary[$k]['content'] = html_entity_decode($v['content']);
                $comment = M('diary_comment')->where('DIA_ID =' . $v['dia_id'])->select();
                if ($comment) {
                    $diary[$k]['comment'] = $comment;
                    foreach ($diary[$k]['comment'] as $key => $row) {
                        $diary[$k]['comment'][$key]['user_id'] = getChineseName($row['user_id']);
                    }
                }
            }
            $newData = array_slice($diary, $start, 10);
            if ($diary) {
                $return['status'] = 1;
                $return['user_name'] = getChineseName($data['user_id']);
                $return['data'] = $diary;
                $return['count'] = $count;
                $page = new \Think\AjaxPage($count, $limit);
                $page->setConfig('prev', '上一页');
                $page->setConfig('next', '下一页');
                $page->setConfig('first', '首页');
                $page->setConfig('last', '尾页');
                $page->rollPage = 5;
                $return['page'] = $page->pageList_ajax('searchDiary');
            } else {
                $return['status'] = 0;
            }
//            print_r($return);die;
            $this->ajaxReturn($return);
        }
        if (I('is_view') == 1) {//查看全公司
            $department = M('department')->field('dept_id,dept_name')->select();
        } elseif (I('is_view') == 2) {//查看本部门
            if (I('dept_id')) {
                $dmap['dept_id'] = I('dept_id');
            } else {
                $dmap['dept_id'] = session('dept_id');
            }
            $department = M('department')->field('dept_id,dept_name')->where($dmap)->select();
        }
        foreach ($department as $k => $v) {
            $department[$k]['dept_user'] = M('user')->field('user_id,user_name')->where('dept_id = ' . $v['dept_id'])->select();
        }
//        echo '<pre>',print_r($department);die;
        $this->department = $department;
        $this->is_view = I('is_view');
        $this->user_dept = session('dept_id');

        //点击头像查看日志
        $p = I('get.p');
        $limit = 10;
        $infos = M('diary')->where('user_id="' . I('user_id') . '"')->order('dia_date desc')->page($p, $limit)->select();
        foreach ($infos as $key => $row) {
            $comment = M('diary_comment')->where('dia_id="' . $row['dia_id'] . '"')->order('send_time desc')->select();
            if ($comment) {
                $infos[$key]['comment'] = $comment;
            }
        }
        $this->infos = $infos;
        $count = M('diary')->where('user_id="' . I('user_id') . '"')->count();

        $this->page = $this->pageLists($count, $limit);
//        print_r($infos);
        $this->infoCount = $count;
        $this->display();
    }

    //公文浏览
    public function document() {
        $p = I('get.p');
        $limit = $this->limit;
        $con = I('get.');
        $document = $this->getDocumentData($con, $p, $limit);
        $count = $document['count'];
        unset($document['count']);
        $this->document = $document;
        $this->count = $count;
        $this->page = $this->pageLists($count, $limit);
        $this->display();
    }

    //获取公文数据
    public function getDocumentData($con, $p, $limit) {
        $map = [];
        if (isset($con['is_read']) && $con['is_read'] == 2) {
            $this->is_read = $con['is_read'];
            $map['readers'] = array('like', '%' . session('user_id') . '%');
        }
        if (isset($con['from_id']) && $con['from_id'] != '') {
            $this->from_id = $con['from_id'];
            $map['from_id'] = array('like', '%' . $con['from_id'] . '%');
        }
        if (isset($con['type_id']) && $con['type_id'] != '') {
            $this->type_id = $con['type_id'];
            $map['type_id'] = array('eq', $con['type_id']);
        }
        if (isset($con['subject']) && $con['subject'] != '') {
            $this->subject = $con['subject'];
            $map['subject'] = array('like', '%' . $con['subject'] . '%');
        }
        if (isset($con['send_time']) && $con['send_time'] != '') {
            $this->send_time = $con['send_time'];
            $map['send_time'] = array('like', '%' . $con['send_time'] . '%');
        }
        if (isset($con['content']) && $con['content'] != '') {
            $this->content = $con['content'];
            $map['content'] = array('like', '%' . $con['content'] . '%');
        }
        if ($con['is_read'] == 1 || $con || empty($con)) {
            if ($con['is_read'] == 1) {
                $map['readers'] = array(array('notlike', '%' . session('user_id') . '%'), array('exp', 'IS NULL'), 'or');
                $this->is_read = $con['is_read'];
            }
            //部门条件符合
            $where['to_id'] = array(array('like', '%ALL_DEPT%'), array('like', '%' . session('dept_id') . '%'), 'or');

            //角色条件符合
            $curUserPriv = session('user_priv') . ',' . session('user_priv_other');
            $curUserPrivArr = explode(',', substr($curUserPriv, 0, -1));
            foreach ($curUserPrivArr as $priv) {
                $privCon[] = array(array('like', '%' . ',' . $priv . ',' . '%'), array('like', $priv . ',%'), 'or');
            }
            $privCon[] = 'or';
            $where['priv_id'] = $privCon;

            //人员符合
            $where['user_id'] = array('like', '%' . session('user_id') . '%');
            $where['_logic'] = 'or';
            $map[] = $where;
            $map['_logic'] = 'and';
        }


        $count = M('document')->where($map)->count();
        if ($limit) {
            $document = M('document')->field('document_id,from_dept,from_id,to_id,subject,content,send_time,begin_date,end_date,priv_id,user_id,type_id,readers')->where($map)->order('send_time desc')->page($p, $limit)->select();
        } else {
            $document = M('document')->field('document_id,from_dept,from_id,to_id,subject,content,send_time,begin_date,end_date,priv_id,user_id,type_id,readers')->where($map)->order('send_time desc')->select();
        }

        foreach ($document as $k => $v) {
            $deptName = [];
            $document[$k]['begin_date'] = date("Y-m-d", $v['begin_date']);
            $document[$k]['end_date'] = date("Y-m-d", $v['end_date']);

            if ($v['to_id'] == 'ALL_DEPT') {
                $document[$k]['to_id'] = '全体部门';
            } else {
                $deptNameArr = M('department')->field('dept_name')->where('dept_id in(' . substr($v['to_id'], 0, -1) . ')')->select();
                foreach ($deptNameArr as $key => $value) {
                    $deptName[] = $value['dept_name'];
                }
                $document[$k]['to_id'] = implode(',', $deptName);
            }
            if ($v['priv_id']) {//发布角色范围
                $userPrivArr = M('user_priv')->field('priv_name')->where('user_priv in(' . substr($v['priv_id'], 0, -1) . ')')->select();
                foreach ($userPrivArr as $key => $value) {
                    $privName[] = $value['priv_name'];
                }
                $document[$k]['priv_id'] = implode(',', $privName);
            }
            if ($v['user_id']) {//发布人员范围
                $userNameArr = explode(',', substr($v['user_id'], 0, -1));
                foreach ($userNameArr as $u_value) {
                    $userName[] = M('user')->where('user_id = "' . $u_value . '"')->getField('user_name');
                }
                $document[$k]['user_id'] = implode(',', $userName);
            }
            if (strstr($v['readers'], session('user_id'))) {
                $document[$k]['is_read'] = 2; //已读
            } else {
                $document[$k]['is_read'] = 1; //未读
            }
            if ($v['begin_date'] == '0000-00-00') {
                $document[$k]['begin_date'] = date("Y-m-d");
            }
        }
        $document['count'] = $count;
        return $document;
    }

    //读取公文内容
    public function readDocument() {
        $document_id = I('document_id');
        if (I('is_manage')) {
            $this->is_manage = I('is_manage');
        }
        if (I('model')) {
            $this->model = I('model');
        }

        if (IS_AJAX) {
            $lists = $this->getDocumentData($con, '', '');
            unset($lists['count']);
            $len = count($lists) - 1;
            $status = I('status');
            foreach ($lists as $key => $row) {
                if ($row['document_id'] == $document_id) {
                    if ($status == 'prev') {
                        //取前一条
                        $document = $key != 0 ? $lists[$key - 1] : [];
                    } else {
                        $document = $key < $len ? $lists[$key + 1] : [];
                    }
                }
            }
            if (empty($document)) {
                $return['status'] = 0;
                $return['info'] = $status == 'prev' ? '已经是第一条公告' : '已经是最后一条公告';
            } else {
                $return['url'] = U('readDocument', array('document_id' => $document['document_id']));
                $return['document_id'] = $notify['document_id'];
                $return['status'] = 1;
            }
            $this->ajaxReturn($return);
        }

        $map['document_id'] = $document_id;
        $document = M('document')->field('document_id,from_id,from_dept,to_id,subject,content,send_time,type_id,auditer,keyword,attachment_id,attachment_name,last_editor,last_edit_time,readers,uploads,uploads_url')->where($map)->find();
        $document['keyword'] = str_replace(',', '&nbsp', $document['keyword']);
        if ($document['attachment_name']) {
            $document['attachment_name'] = explode('*', substr($document['attachment_name'], 0, -1));
        }
        if ($document['uploads']) {
            $document['uploads'] = explode(';', $document['uploads']);
            $document['uploads_url'] = explode(';', $document['uploads_url']);
        }

        //更新阅读者
        if (!strstr($document['readers'], session('user_id'))) {
            $readers = $document['readers'] . session('user_id') . ",";
            $sql = "update `document` set readers = '" . $readers . "' where document_id = " . $document_id;
            M('')->execute($sql);
        }

        $this->data = $document;
        $this->display();
    }

    //个人设置
    public function userinfo() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['birthday'] = $data['bir_year'] . '-' . $data['bir_mon'] . '-' . $data['bir_day'];
            $res = M('user')->where('user_id = "' . $data['user_id'] . '"')->save($data);
            if ($res !== false) {
                $return['status'] = 1;
                $return['info'] = '修改成功';
            }
            $this->ajaxReturn($return);
        }
        for ($i = 0; $i < 60; $i++) {
            $year[] = $i + 1958;
        }
        for ($i = 0; $i < 12; $i++) {
            $month[] = $i + 1;
        }
        for ($i = 0; $i < 31; $i++) {
            $day[] = $i + 1;
        }
        $userinfo = M('user')->field('user_id,user_name,sex,birthday,add_home,post_no_home,tel_no_home,mobil_no,email')->where('user_id = "' . session('user_id') . '"')->find();
        if ($userinfo['birthday'] != "0000-00-00") {
            $b_year = date("Y", strtotime($userinfo['birthday']));
            $b_month = date("m", strtotime($userinfo['birthday']));
            $b_day = date("d", strtotime($userinfo['birthday']));
            $userinfo['b_year'] = $b_year;
            $userinfo['b_month'] = $b_month;
            $userinfo['b_day'] = $b_day;
            //获取生肖
            $userinfo['zodiac'] = get_animal($b_year);
            //获取星座
            $userinfo['con'] = get_zodiac_sign($b_month, $b_day);
        }
        $this->year = $year;
        $this->month = $month;
        $this->day = $day;
        $this->userinfo = $userinfo;
        $this->display();
    }

    //判断原密码是否正确
    public function checkPass() {
        $pass0 = I('pass0');
        $password = M('user')->where('user_id = "' . session('user_id') . '"')->getField('password');
        $map['PASSWORD'] = crypt($pass0, $password);
        $row = M('user')->where($map)->find();
        if (!$row) {
            $return['status'] = 1;
            $return['info'] = '原密码填写错误！';
        } else {
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }

    //修改OA密码
    public function setPass() {
        $data = I('post.');
        $pdata['password'] = crypt($data['pass1']);
        $pdata['last_pass_time'] = date("y-m-d H:i:s");
        $res = M('user')->where('user_id = "' . session('user_id') . '"')->save($pdata);
        if ($res !== false) {
            $return['info'] = '修改密码成功';
        }
        $this->ajaxReturn($return);
    }

    //收邮件(当月或指定时间)
    private function newEmailList() {
        $userid = M('user')->where('user_id="' . session('user_id') . '"')->getField('email');

        return getExmailList('2018-5-10', '2018-8-10', 2, $userid);
    }

    //日程安排
    public function schedule() {
        if (IS_POST) {
            $map['user_id'] = session('user_id');
            $map['status'] = 0;
            $data = M('calendar')->field('id,user_id,title,start_time,end_time,flag_color')->where($map)->select();
            foreach ($data as $key => $row) {
                $ndata[$key]['title'] = $row['title'];
                $ndata[$key]['start'] = date('Y-m-d H:i', $row['start_time']);
                $ndata[$key]['end'] = date('Y-m-d H:i', $row['end_time']);
//                $ndata[$key]['url'] =  U('Personal/event',array('id'=>$row['id'])); 
                $ndata[$key]['id'] = $row['id'];
                $ndata[$key]['allDay'] = true;
                $ndata[$key]['color'] = $row['flag_color'];
            }
            $this->ajaxReturn($ndata);
        }

        //修改过期日程状态
        $map['_string'] = 'end_time != 0 and end_time < '. time();
        $data['status'] = 1;
        M('calendar')->where($map)->save($data);

        $this->display();
    }

    //日程弹窗
    public function event() {
        if (IS_AJAX) {
            $data = I('post.');
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = $data['end_time'] ? strtotime($data['end_time']) : '';
            $data['remind_time'] = strtotime($data['remind_time']);
            if ($data['is_send_user'] == 1 || $data['send_user']) {
                $data['user_id'] = $data['send_user'];
                $data['create_user'] = session('user_id');
            } else {
                $data['user_id'] = session('user_id');
            }

            if ($data['id']) {
                if ($data['finish'] == 1) {
                    $data['status'] = 1;
                }
                if ($data['end_time'] == '') {
                    $data['status'] = 0;
                }
                $res = M('calendar')->save($data);
            } else {
                $data['create_time'] = time();
                $res = M('calendar')->add($data);
            }

            if ($res !== false) {
                $return = ['info' => '提交成功', 'icon' => 6, 'parent' => 1, 'status' => 1];
            } else {
                $return = ['info' => '提交失败', 'icon' => 5, 'status' => 1];
            }
            $this->ajaxReturn($return);
        }

        $this->date = I('date');
        $this->info = M('calendar')->find(I('id'));
//print_r($this->info);
        $this->users = M('user')->field('user_id,user_name')->where('dept_id=' . session('dept_id'))->select();

        $this->display();
    }

    //删除日程
    public function delCalendar() {
        $res = M('calendar')->delete(I('id'));
        $return = $res !== false ? ['status' => 1] : ['status' => 0];
        $this->ajaxReturn($return);
    }

}
